package src.activation;



import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import src.utils.XMLValidator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.IOException;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class ActivationSystem extends HttpServlet {
	private static final String STR_SCHEMA_FILE = "incoming_msg.xsd";
	private final String[][] CODES = 
									{	{"OK", "The Activation was successful"}, 
										{"INCOMPLETE", "The provision has yet to be actioned"}, 
										{"UNKNOWN", "The provision identifier is not recognised"} 
									};


	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		try {

			DocumentBuilderFactory 	factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder 		parser	= factory.newDocumentBuilder();
			Document 				doc		= parser.parse(request.getInputStream()); 

			
			String strResponse;
			// check if document is valid against the schema
			 if(checkValidity(doc)){				
				XPath xpath = XPathFactory.newInstance().newXPath();
	
				Object result = xpath.evaluate("/activation/provisionId/text()", doc, XPathConstants.NODE);
				String provisionId = ((Node)result).getTextContent();
	
				strResponse = createResponse(verify(provisionId));
			 }else{
				 // 2 is the code for UNKNOWN -- since it was an invalid request.
				 strResponse = createResponse(2);
			 }
				response.setContentType("text/xml");

			PrintWriter writer = response.getWriter();
			System.out.println(strResponse);
			writer.println(strResponse);
			
			



			writer.flush();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private int verify(String provisionId) {
		if (provisionId.equals("123456")) {
			return 0;
		} else if (provisionId.equals("123455")) {
			return 1;
		} else {
			return 2;
		}
	}

	private String createResponse(int codeIndex) {
		try {

			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();



			Element root = doc.createElement("confirmation");
			doc.appendChild(root);

			Element codeElement = doc.createElement("code");
			codeElement.appendChild(doc.createTextNode(CODES[codeIndex][0]));
			root.appendChild(codeElement);

			Element messageElement = doc.createElement("message");
			messageElement.appendChild(doc.createTextNode(CODES[codeIndex][1]));
			root.appendChild(messageElement);

			TransformerFactory tranFactory = TransformerFactory.newInstance();
			Transformer aTransformer = tranFactory.newTransformer();

			Source src = new DOMSource(doc);
			Result dest = new StreamResult(new StringWriter());
			aTransformer.transform(src, dest);

			return ((StreamResult)dest).getWriter().toString();
		} catch (Exception e) {
		}

		return null;
	}


	/**
	 * Validates the request against the formal request message xml schema
	 * @return
	 */
	private boolean checkValidity(Document doc){
		boolean isValid = false;

		try {
			XMLValidator.validate(doc, new StreamSource(getClass().getResourceAsStream(STR_SCHEMA_FILE)));
			isValid = true;
		} catch (Exception e) {		
			//if we reach here then its invalid
			isValid = false;			
			System.out.println("[activation] did not satisfy schema definition");
		}
		return isValid;
	}

}